﻿using Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinCourseControls.DAL;
using WinCourseControls.Models;

namespace WinCourseControls
{
    public partial class FrmDataGridView : Form
    {
        public FrmDataGridView()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 添加空行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            // dataGridView1.Rows.Add();
            dataGridView1.AllowUserToAddRows = true;//无数据源  
        }

        /// <summary>
        /// 新增数据方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddNew_Click(object sender, EventArgs e)
        {
            //1.方式1
            dataGridView1.Rows.Add(new object[] { 1, "李明", true, "18378909876" });
            //2,添加DataGridViewRow  对象  ：各种类型的单元格
            DataGridViewRow dr = new DataGridViewRow();//行对象
            DataGridViewCell cell0 = new DataGridViewTextBoxCell();
            cell0.Value = 12;
            DataGridViewCell cell1 = new DataGridViewTextBoxCell();
            cell1.Value = "王红";
            DataGridViewCell cell2 = new DataGridViewCheckBoxCell();
            cell2.Value = true;
            DataGridViewCell cell3 = new DataGridViewTextBoxCell();
            cell3.Value = "18709764589";
            dr.Cells.AddRange(cell0, cell1, cell2, cell3);
            dataGridView1.Rows.Add(dr);
        }

        /// <summary>
        /// 单击单元格事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGet_Click(object sender, EventArgs e)
        {
            //无数据源行数据的编辑
            foreach (DataGridViewRow dr in dataGridView1.Rows)
            {
                string name = dr.Cells[1].Value.ToString();//获取名称单元格的值
                                                           //  bool state = Convert.ToBoolean(dr.Cells["colState"].Value);//状态
            }

            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                // var obj = dataGridView1.Rows[i].DataBoundItem;//无数据源时，行数据对象是null
                string name = dataGridView1.Rows[i].Cells[1].Value.ToString();//获取名称单元格的值
            }
        }

        StudentDAL stuDAL = new StudentDAL();
        ClassDAL classDAL = new ClassDAL();
        private void FrmDataGridView_Load(object sender, EventArgs e)
        {

            //DataTable 作为数据源
            //dataGridView2.AutoGenerateColumns = true;//默认自动创建列标题
            //DataTable dtStudents = stuDAL.GetDt("select StuId ,StuName 姓名,Sex,Phone,ClassId from StudentInfos where IsDeleted=0", 1);
            //dtStudents.Columns[0].ColumnName = "学号";//列标题改成中文
            //dataGridView2.DataSource = dtStudents;

            //下拉列 提供可选项：数据源  
            List<ClassInfo> classList = classDAL.GetModelList("ClassId,ClassName", "", 0);
            // 找到下拉框列-要先绑定下拉列表数据源
            DataGridViewComboBoxColumn cboCol = dataGridView1.Columns["colClassId"] as DataGridViewComboBoxColumn;
            cboCol.DataSource = classList;
            cboCol.DisplayMember = "ClassName";
            cboCol.ValueMember = "ClassId";

            //信息栏的下拉框初始化
            cboClasses.DataSource = classList;
            cboClasses.DisplayMember = "ClassName";
            cboClasses.ValueMember = "ClassId";

            //List 作为数据源   手动添加列   各列的绑定属性名
            ReloadStudentList();
        }

        /// <summary>
        /// 数据加载-刷新列表数据
        /// </summary>
        private void ReloadStudentList()
        {
            int isDeleted = chkDel.Checked ? 1 : 0;
            dataGridView1.AutoGenerateColumns = false;//不创建列
            List<StudentInfo> stuList = stuDAL.GetModelList("", "", isDeleted);
            dataGridView1.DataSource = stuList;//List列表作为数据源
            if (chkDel.Checked)
            {   // 恢复数据模式
                dataGridView1.Columns["colEdit"].Visible = false; 
                dataGridView1.Columns["colDel"].Visible = false;
                dataGridView1.Columns["colRecover"].Visible = true;
                dataGridView1.Columns["colRemove"].Visible = true;
            }
            else
            {   // 正常模式
                dataGridView1.Columns["colEdit"].Visible = true;
                dataGridView1.Columns["colDel"].Visible = true;
                dataGridView1.Columns["colRecover"].Visible = false;
                dataGridView1.Columns["colRemove"].Visible = false;
            }
        }

        /// <summary>
        /// 单元格单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //单击的行是数据行 index>-1
            //当前点击的单元格
            if (e.RowIndex > -1)  // 方式一
            {
                DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                MessageBox.Show(cell.Value.ToString());
            }

            // 方式二
            DataGridViewCell cell2 = sender as DataGridViewCell;
            if (cell2 != null)
            {
                MessageBox.Show(cell2.Value.ToString());
            }

        }

        /// <summary>
        /// 临时保存选中学员ID
        /// </summary>
        List<int> chkIds = new List<int>();
        /// <summary>
        /// 要修改的学生ID
        /// </summary>
        int editStuId = 0;
        /// <summary>
        /// 单击单元格内容时发生的增、删、改、等操作
        /// 一般用于CheckBox，button，下拉列表，链接等
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 获取单元格数据
            DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
            // 获取行数据
            StudentInfo stu = dataGridView1.Rows[e.RowIndex].DataBoundItem as StudentInfo;
            {   // 复选框操作-配合CurrentCellDirtyStateChanged事件一起使用选中状态不需要反着来
                //if(cell is DataGridViewCheckBoxCell)
                //{
                //    if(cell.ColumnIndex==0)
                //    {  // 列值为null的复选框操作 -- FormattedValue:格式化显示值
                //        if(cell.FormattedValue.ToString()=="True") // 点击前的数据
                //        {  
                //            //MessageBox.Show("True");
                //            chkIds.Remove(stu.StuId);
                //        }
                //        else
                //        {
                //            //MessageBox.Show("False");
                //            chkIds.Add(stu.StuId);
                //        }
                //    }
                //    else
                //    {   // 列值不为null的复选框操作
                //        MessageBox.Show(cell.Value.ToString());
                //    }
                //}
            }

            if (cell.FormattedValue.ToString() == "修改")
            {
                editStuId = stu.StuId;
                txtName.Text = stu.StuName;
                txtPhone.Text = stu.Phone;
                cboClasses.SelectedValue = stu.ClassId;
                if (stu.Sex == "男")
                    rbtnMale.Checked = true;
                else
                    rbtnFemale.Checked = true;

            }
            else if (cell.FormattedValue.ToString() == "删除")
            {
                if (MessageBox.Show("您确定要删除吗?", "删除提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)//
                {
                    bool bl = stuDAL.Delete(stu.StuId, 0, 1);//逻辑删除  改删除标识
                    if (bl)
                    {
                        //成功提示并移除该行
                        MessageBox.Show("删除成功！");
                        //移除
                        //1.刷新列表数据
                        // ReloadStudentList();//重新到数据库获取数据-了解一般不用

                        //2.刷新列表数据方式二
                        List<StudentInfo> list = dataGridView1.DataSource as List<StudentInfo>; // 获取数据源
                        dataGridView1.DataSource = null;  // 断开数据源-直接修改数据源列表不会即时更新显示
                        list.Remove(stu);  // 移除数据
                        dataGridView1.DataSource = list;  // 重新绑定数据源
                    }
                    else
                    {
                        //失败提示并返回
                        return;
                    }
                }
            }
            else if (cell.FormattedValue.ToString() == "恢复")
            {
                if (MessageBox.Show("您确定要恢复吗?", "恢复提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)//
                {
                    bool bl = stuDAL.Delete(stu.StuId, 0, 0);//逻辑删除  改删除标识为0
                    if (bl)
                    {
                        //成功提示并移除该行  从已删除列表中移除
                        MessageBox.Show("恢复成功！");
                        //移除
                        //1.
                        //ReloadStudentList();//重新到数据库获取数据
                        //2.
                        List<StudentInfo> list = dataGridView1.DataSource as List<StudentInfo>; // 获取数据源
                        dataGridView1.DataSource = null;  // 断开数据源-直接修改数据源列表不会即时更新显示
                        list.Remove(stu);  // 移除数据
                        dataGridView1.DataSource = list;  // 重新绑定数据源
                    }
                    else
                    {
                        //失败提示并返回
                        return;
                    }
                }
            }
            else if (cell.FormattedValue.ToString() == "移除")
            {
                if (MessageBox.Show("您确定要移除吗?", "移除提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)//
                {
                    bool bl = stuDAL.Delete(stu.StuId, 1, 2);//真删除 
                    if (bl)
                    {
                        //成功提示并移除该行  从已删除列表中移除
                        MessageBox.Show("移除成功！");
                        //移除
                        //1.
                        //ReloadStudentList();//重新到数据库获取数据
                        //2.
                        List<StudentInfo> list = dataGridView1.DataSource as List<StudentInfo>; // 获取数据源
                        dataGridView1.DataSource = null;  // 断开数据源-直接修改数据源列表不会即时更新显示
                        list.Remove(stu);  // 移除数据
                        dataGridView1.DataSource = list;  // 重新绑定数据源
                    }
                    else
                    {
                        //失败提示并返回
                        return;
                    }
                }
            }
        }

        /// <summary>
        /// 单元格双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
            MessageBox.Show("Double:" + cell.Value.ToString());
        }

        /// <summary>
        /// 单元格内容改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                StudentInfo stu = dataGridView1.Rows[e.RowIndex].DataBoundItem as StudentInfo;
                //MessageBox.Show(cell.Value.ToString());
                if (dataGridView1.Columns[e.ColumnIndex].Name == "colChk")
                {
                    if (cell.FormattedValue.ToString() == "True")
                    {
                        chkIds.Add(stu.StuId);
                    }
                    else
                    {
                        chkIds.Remove(stu.StuId);
                    }
                }
            }
        }

        /// <summary>
        /// 单元格因其内容改变而改变的事件
        /// 用于辅助单元格内容改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            // 固定写法
            if (dataGridView1.IsCurrentCellDirty)//单元格未提交
            {   // 单元格内容提交但不结束编辑模式-这样就可以触发单元格内容改变事件
                dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        /// <summary>
        /// 确定按钮提交新增/修改的学员信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("选择的学号有：" + string.Join(",", chkIds));
            //暂时不考虑验证逻辑控制
            //信息封装
            StudentInfo stuInfo = new StudentInfo()
            {
                StuId = editStuId,
                StuName = txtName.Text.Trim(),
                Sex = rbtnMale.Checked ? "男" : "女",
                Phone = txtPhone.Text.Trim(),
                ClassId = cboClasses.SelectedValue.GetInt()
            };
            if (editStuId > 0)
            {
                bool blUpdate = stuDAL.Update(stuInfo, "StuId,StuName,Sex,Phone,ClassId");
                if (blUpdate)
                {
                    MessageBox.Show("修改成功！");
                    List<StudentInfo> list = dataGridView1.DataSource as List<StudentInfo>; // 获取数据源
                    dataGridView1.DataSource = null;  // 断开数据源
                    // 修改数据
                    StudentInfo stu = list.Find(s => s.StuId == editStuId); 
                    stu.StuName = stuInfo.StuName;
                    stu.Phone = stuInfo.Phone;
                    stu.Sex = stuInfo.Sex;
                    stu.ClassId = stuInfo.ClassId;
                    dataGridView1.DataSource = list; // 重新绑定数据源
                }
            }
            else
            {
                int newId = stuDAL.Add(stuInfo, "StuName,Sex,Phone,ClassId", 1);
                if (newId > 0)
                {
                    MessageBox.Show("学生信息新增成功！");
                    stuInfo.StuId = newId;
                    List<StudentInfo> list = dataGridView1.DataSource as List<StudentInfo>; // 获取数据源
                    dataGridView1.DataSource = null;  // 断开数据源
                    list.Add(stuInfo);
                    dataGridView1.DataSource = list;  // 重新绑定数据源
                }

            }
        }

        
        /// <summary>
        /// 已删除复选框勾选
        /// 正常模式和恢复模式复选框改变事件
        /// 用于切换列表显示数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkDel_CheckedChanged(object sender, EventArgs e)
        {
            // 刷新列表数据
            ReloadStudentList();
        }

        /// <summary>
        /// 全选复选框
        /// 批量全选和取消全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow item in dataGridView1.Rows)
            {
                // 通过列标题名称获取单元格
                DataGridViewCell cell = item.Cells["colChk"];
                cell.Value = chkAll.Checked;  // 设置选中
            }
        }

        /// <summary>
        /// 批量删除按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确定要删除这些学生信息吗?", "删除提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                bool bl = stuDAL.DeleteList(chkIds, 0, 1);
                if (bl)
                {
                    MessageBox.Show("删除成功！");
                    //ReloadStudentList();//刷新列表

                    {   // 批量刷新列表
                        List<StudentInfo> list = dataGridView1.DataSource as List<StudentInfo>;
                        dataGridView1.DataSource = null;
                        var delList = list.Where(s => chkIds.Contains(s.StuId)).ToList();
                        delList.ForEach(s => list.Remove(s));
                        dataGridView1.DataSource = list;
                    }

                }
            }
        }

        /// <summary>
        /// 批量恢复按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRecover_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确定要恢复这些学生信息吗?", "恢复提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                bool bl = stuDAL.DeleteList(chkIds, 0, 0);
                if (bl)
                {
                    MessageBox.Show("恢复成功！");
                    //ReloadStudentList();//刷新列表
                    {
                        // 批量恢复列表
                        List<StudentInfo> list = dataGridView1.DataSource as List<StudentInfo>;
                        dataGridView1.DataSource = null;
                        var delList = list.Where(s => chkIds.Contains(s.StuId)).ToList();
                        delList.ForEach(s => list.Remove(s));
                        dataGridView1.DataSource = list;
                    }

                }
            }
        }
    }
}
